<?php

namespace app\api\controller;

use addons\shopro\service\order\OrderDispatch;
use addons\shopro\service\user\User as UserService;
use addons\shopro\service\Wallet as WalletService;
use app\admin\model\Children;
use app\admin\model\market\Acceleration;
use app\admin\model\shopro\goods\SkuPrice;
use app\admin\model\shopro\order\Action;
use app\admin\model\shopro\order\Order;
use app\admin\model\shopro\order\OrderItem;
use app\admin\model\shopro\user\Silverlog;
use app\admin\model\shopro\user\WalletLog;
use app\common\controller\Api;
use app\common\model\GoldenLog;
use app\common\model\GoldLog;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use app\common\model\shopro\DividendLog;
use app\common\model\shopro\ReleaseAccelerateLogModel;
use app\common\model\shopro\ReleaseAccelerateMarketplaceLogModel;
use app\common\model\shopro\ReleaseLog;
use app\common\model\shopro\Shop;
use app\common\model\User;
use app\common\model\Userchildren;
use app\common\model\UserStaticLogModel;
use app\common\model\UserTransformLog;
use fast\Random;
use think\Db;
use think\exception\HttpResponseException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function zhuan(){
        $userModel        = new User();
        $user = $userModel->where('principal', '>', 0)->field('id,principal')->select();

//        foreach ($user as $k=>$v){
//            UserTransformLog::create(['user_id'=>$v['id'],'principal'=>$v['principal']]);
//        }
    }

    /**
     * @menu 分积分
     * @Author:男人的坏
     * @Date:2024-04-15 15:22
     */
    public function fenyong($order, $user)
    {
        $goodsModel        = new \app\admin\model\shopro\goods\Goods();
        $gift_score        = 0;
        $gift_silver       = 0;
        $principal_score   = 0;
        $parent_user_info  = '';
        $parent_user_money = 0;
        if ($user->parent_user_id) {
            $parent_user_info = \app\common\model\User::where(['id' => $user->parent_user_id])->field('id,score,principal,level,is_marketplace,parent_user_id')->find();
        }
        $two_user_money = 0;
        $two_user_info  = '';
        if (!empty($parent_user_info->parent_user_id)) {
            $two_user_info = \app\common\model\User::where(['id' => $parent_user_info->parent_user_id])->field('id,score,principal,level,is_marketplace')->find();
        }
        $user_ids     = \app\common\model\User::where(['parent_user_id' => $user->id])->column('id');
        $is_shichang  = \app\admin\model\shopro\order\Order::where(['status' => 'paid'])->whereIn('user_id',
            $user_ids)->count();
        $parent_score = 0;
        $golen_scale  = 0;
        $slive_scale  = 0;
        foreach ($order['items'] as $k => $v) {
            $goodsInfo = $goodsModel->where(['id' => $v->goods_id, 'type' => 'normal'])->find();
            if ($goodsInfo) {
                $goods_golen_scale = $goodsInfo['golen_scale'];
                if ($goods_golen_scale) {
                    $golen_scale = $goods_golen_scale / 100;        //金豆比例
                    $slive_scale = (100 - $goods_golen_scale) / 100;//银豆比例
                }
                $principal_score    = $order['order_amount'];
                $userTransformArray = ['user_id' => $user->id, 'goods_id' => $v->goods_id];
                $userTransformInfo  = UserTransformLog::where($userTransformArray)->find();
                if ($userTransformInfo) {
                    $userTransformInfo->setInc('principal', $principal_score);
                } else {
                    $userTransformArray['principal'] = $principal_score;
                    UserTransformLog::create($userTransformArray);
                }
                if ($goodsInfo->marketplace_times > 0) {
                    if ($is_shichang) {
                        $gift_score = bcmul($order['order_amount'], $goodsInfo->marketplace_times);
                    }

                    UserStaticLogModel::create(['user_id'     => $user->id,
                                                'order_id'    => $order['id'],
                                                'goods_id'    => $v->goods_id,
                                                'money'       => $principal_score,
                                                'rebate_time' => strtotime(date('Y-m-d', 30 * 86400 + time()))
                    ]);
                }
                if ($goodsInfo->type == 'normal') {
                    if ($parent_user_info) {
                        if ($parent_user_info->principal || $parent_user_info->score) {
                            $parent_user_money = bcmul($order['order_amount'], ($goodsInfo->one_scale / 100), 2);
                        }
                        if ($parent_user_info->is_marketplace == 0) {
                            $goods_id = OrderItem::where(['user_id' => $parent_user_info->id])->value('goods_id');
                            if ($goods_id) {
                                $parent_user_goods = \app\admin\model\shopro\Goods::where(['id' => $goods_id, 'type' => 'normal'])->find();
                                if (!empty($parent_user_goods->marketplace_times)) {
                                    $parent_score                     = bcmul($parent_user_info->principal,
                                        $parent_user_goods->marketplace_times);
                                    $parent_user_info->is_marketplace = 1;
                                    $parent_user_info->save();

                                }
                            }
                        }
                    }
                    if ($two_user_info) {
                        if ($two_user_info->principal || $two_user_info->score) {
                            $two_user_money = bcmul($order['order_amount'], ($goodsInfo->two_scale / 100), 2);
                        }
                    }
                }
                //赠送银豆
                if ($goodsInfo->silver_type == 'silver_scale_type') {
                    $gift_silver += bcmul($v->pay_fee, ($goodsInfo->silver_type_num / 100), 2);
                } elseif ($goodsInfo->firepower_type == 'silver_immobilization') {
                    $gift_silver = $goodsInfo->silver_type_num;
                }
            }
        }
        //倍数积分
        $params['id']  = $order['user_id'];
        $params['ext'] = ['order_id' => $order['id']];
        if ($gift_score) {
            $params['type']   = 'score';
            $params['amount'] = $gift_score;
            $params['memo']   = '自购奖励';
            if($params['amount'] > 0){
                Db::transaction(function () use ($params) {
                    return WalletService::change($params['id'], $params['type'], $params['amount'], 'release',
                        $params['ext'],
                        $params['memo']);
                });
            }

        }
        if ($parent_score > 0) {
            Db::transaction(function () use ($parent_user_info, $parent_score, $order) {
                return WalletService::change($parent_user_info->id, 'score', $parent_score, 'release',
                    ['order_id' => $order['user_id']],
                    '动态积分');
            });
            $parent_user_info->score += $parent_score;
        }
        //本金
        if ($principal_score > 0) {
            $params['type']   = 'principal';
            $params['amount'] = $principal_score;
            $params['memo']   = '自购奖励';
            Db::transaction(function () use ($params) {
                return WalletService::change($params['id'], $params['type'], $params['amount'], 'order', $params['ext'],
                    $params['memo']);
            });

        }
        //赠送银豆
        if ($gift_silver > 0) {
            $params['type']   = 'silver';
            $params['amount'] = $gift_silver;
            $params['memo']   = '自购奖励';
            Db::transaction(function () use ($params) {
                return WalletService::change($params['id'], $params['type'], $params['amount'], 'order', $params['ext'],
                    $params['memo']);
            });
        }
        if ($parent_user_money > 0) {
            if ($parent_user_info->principal >= $parent_user_money) {
                $this->RecommendedFenyong($parent_user_info, $parent_user_money, '推荐收益', 'principal',$golen_scale,$slive_scale);
            } else {
                if ($parent_user_info->principal == 0) {
                    if ($parent_user_info->score > 0) {
                        if ($parent_user_info->score >= $parent_user_money) {
                            $this->RecommendedFenyong($parent_user_info, $parent_user_money, '推荐收益', 'score',$golen_scale,$slive_scale);
                        } else {
                            $this->RecommendedFenyong($parent_user_info, $parent_user_info->score, '推荐收益', 'score',$golen_scale,$slive_scale);
                        }
                    }
                } else {
                    $parent_user_money -= $parent_user_info->principal;
                    $this->RecommendedFenyong($parent_user_info, $parent_user_info->principal, '推荐收益', 'principal',$golen_scale,$slive_scale);
                    if ($parent_user_info->score  >= $parent_user_money) {
                        $this->RecommendedFenyong($parent_user_info, $parent_user_money, '推荐收益', 'score',$golen_scale,$slive_scale);
                    } else {
                        $this->RecommendedFenyong($parent_user_info, $parent_user_info->score, '推荐收益', 'score',$golen_scale,$slive_scale);
                    }
                }

            }
        }

        if ($two_user_money > 0) {
            if ($two_user_info->principal >= $two_user_money) {
                $this->RecommendedFenyong($two_user_info, $two_user_money, '间推收益', 'principal',$golen_scale,$slive_scale);
            } else {
                if ($two_user_info->principal == 0) {
                    if ($two_user_info->score > 0) {
                        if ($two_user_info->score >= $two_user_money) {
                            $this->RecommendedFenyong($two_user_info, $two_user_money, '间推收益', 'score',$golen_scale,$slive_scale);
                        } else {
                            $this->RecommendedFenyong($two_user_info, $two_user_info->score, '间推收益', 'score',$golen_scale,$slive_scale);
                        }
                    }
                } else {
                    $two_user_money -= $two_user_info->principal;
                    $this->RecommendedFenyong($two_user_info, $two_user_info->principal, '间推收益', 'principal',$golen_scale,$slive_scale);
                    if ($two_user_info->score >= $two_user_money) {
                        $this->RecommendedFenyong($two_user_info, $two_user_money, '间推收益', 'score',$golen_scale,$slive_scale);
                    } else {
                        $this->RecommendedFenyong($two_user_info, $two_user_info->score, '间推收益', 'score',$golen_scale,$slive_scale);
                    }
                }
            }
        }
        if($order['order_amount'] > 0){
            jicha($user, $order['order_amount'], $user->level);
        }
    }


    public function RecommendedFenyong($userInfo, $release, $memo, $type, $golen_scale, $slive_scale)
    {
//        $golen_scale       = config('site.golen_scale') / 100;        //金豆比例
//        $slive_scale       = (100 - config('site.golen_scale')) / 100;//银豆比例
        if($release > 0){
            WalletService::change($userInfo->id, $type, -$release, 'release',
                ['level' => $userInfo->level],
                $memo);
            $golden = bcmul($release, $golen_scale, 2);
            if ($golden > 0) {
                WalletService::change($userInfo->id, 'golden', $golden, 'release_golden',
                    ['level' => $userInfo->level],
                    $memo);
            }
            $slive = bcmul($release, $slive_scale, 2);
            if ($slive > 0) {
                WalletService::change($userInfo->id, 'silver', $slive, 'release_slive ',
                    ['level' => $userInfo->level],
                    $memo);
            }
        }
    }

    public function ceshi(){
        $order = Order::where(['id'=>387])->find();
        $user =  \app\admin\model\User::where(['id'=>$order->user_id])->find();
        $this->fenyong($order,$user);
//        dump(cache('next_rebate_time'));
        exit();
        $userModel        = new User();
        $model            = new UserStaticLogModel();
        $user_idArr       = $userModel->where('principal', '>', 0)->column('id');
        $data             = $model->with(['user'])->where('status', '=', 1)->whereIn('user_id',
            $user_idArr)->where('rebate_time', '<', time())->select();
        dump($model->getLastSql());
        var_dump($data);exit();
        dump(strtotime(date('Y-m-d',30*86400+time())));exit();
        $partner_day = 7;
        $sta_time      = strtotime('-'.$partner_day.' days', strtotime(date('Y-m-d')));
        $userModel        = new User();
        $model            = new UserStaticLogModel();
        $rebate_time = 86400*$partner_day +time();
        dump($rebate_time);exit();
        $user_idArr       = $userModel->where('principal', '>', 0)->column('id');
        $data  = $model->with(['user'])->where('status','=',1)->whereIn('user_id', $user_idArr)->where('rebate_time','<',time())->select();
//        $order = Order::where(['id'=>266])->with(['items'])->find();
//        $user = User::where(['id'=>$order->user_id])->find();
//        // 添加消费金额
////        UserService::consume($user, $order['order_amount']);
//        jicha($user, $order['order_amount'], $user->level);
//        $id_arr = User::where(['id'=>['neq','761']])->delete();
//        MoneyLog::whereIn('user_id',$id_arr)->delete();
//        Silverlog::whereIn('user_id',$id_arr)->delete();
//        ScoreLog::whereIn('user_id',$id_arr)->delete();
//        GoldLog::whereIn('user_id',$id_arr)->delete();
//       $r = Userchildren::where('member_id','<>',761)->delete();
//       dump($r);
//        $ids_arr =  Userchildren::where('member_id',761)->column('children_id');
//        $userModel = new User();
//       $r= $userModel->whereNotIn('id', $ids_arr)->delete();
//        dump($r);
    }



}
